package com.ddxcloud.movie.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.ddxcloud.common.annotation.RepeatSubmit;
import com.ddxcloud.common.constants.RedisKeyConstant;
import com.ddxcloud.common.handler.BusinessException;
import com.ddxcloud.common.sms.utils.SmsUtil;
import com.ddxcloud.common.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Api("短信")
public class SmsController {

    @Resource
    SmsUtil smsUtil;

    @Resource
    RedisUtil redisUtil;

    /**
     * 发送短信
     * @param phone
     * @throws IOException
     */
    @RepeatSubmit
    @Operation(summary = "发送短信")
    @GetMapping("/sendSms")
    public void sendSms(String phone) throws IOException {
        if (phone == null || phone.isEmpty()) {
            throw new BusinessException("请输入手机号码");
        } else if (!Validator.isMobile(phone)) {
            throw new BusinessException("请输入正确的手机号码");
        }
        String redisKey = RedisKeyConstant.SMS_LOGIN + phone;
        if (redisUtil.hasKey(redisKey)) {
            throw new BusinessException("请勿重复发送");
        } else {
            String codes = RandomUtil.randomNumbers(4);
            redisUtil.setEx(redisKey, codes, 10, TimeUnit.MINUTES);
            String content = "验证码：" + codes + "，10分钟内有效，请勿向任何人转发或泄露。";
            smsUtil.sendMsg(phone, content);
        }
    }
}
